package com.huitong.common.mybatis.config;

import com.huitong.common.mybatis.encrypt.EncryptorManager;
import com.huitong.common.mybatis.interceptor.DecryptInterceptor;
import com.huitong.common.mybatis.interceptor.EncryptInterceptor;
import com.huitong.common.mybatis.properties.EncryptCustomProperties;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * 敏感字段加密配置
 *
 * @author fromdrowning
 * @date 2024/4/11 22:15
 */
@AutoConfiguration
@EnableConfigurationProperties(EncryptCustomProperties.class)
@ConditionalOnProperty(value = "mybatis.encrypt.enabled", havingValue = "true")
public class EncryptConfiguration {

    /**
     * 敏感字段加密管理器配置
     *
     * @param encryptCustomProperties 敏感字段加密自定义配置
     * @return 敏感字段加密管理器
     */
    @Bean
    public EncryptorManager encryptManagerCustomizer(EncryptCustomProperties encryptCustomProperties) {
        return new EncryptorManager(encryptCustomProperties);
    }

    /**
     * 入参加密拦截器配置
     *
     * @param encryptorManager 敏感字段加密管理器
     * @return 入参加密拦截器
     */
    @Bean
    public Interceptor decryptInterceptorCustomizer(EncryptorManager encryptorManager) {
        return new DecryptInterceptor(encryptorManager);
    }

    /**
     * 出参解密拦截器配置
     *
     * @param encryptorManager 敏感字段加密管理器
     * @return 出参解密拦截器
     */
    @Bean
    public Interceptor encryptInterceptorCustomizer(EncryptorManager encryptorManager) {
        return new EncryptInterceptor(encryptorManager);
    }
}
